// 移除复制限制功能
function removeAntiCopy() {
    const removeLimit = () => {
        document.querySelectorAll('*').forEach(el => {
            el.style.userSelect = 'text';
            el.oncontextmenu = null;
            el.onselectstart = null;
            el.onselect = null;
            el.oncopy = null;
            el.oncut = null;
            el.onpaste = null;
        });
        
        document.body.oncopy = null;
        document.body.oncut = null;
        document.body.onselectstart = null;
        document.body.oncontextmenu = null;
        
        const style = document.createElement('style');
        style.innerHTML = `
            * {
                -webkit-user-select: text !important;
                -moz-user-select: text !important;
                -ms-user-select: text !important;
                user-select: text !important;
            }
        `;
        document.head.appendChild(style);
    };

    removeLimit();

    const observer = new MutationObserver(removeLimit);
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
}

// 创建浮动按钮
function createTriggerButton() {
    const button = document.createElement('button');
    button.innerHTML = `
        <span class="spider-icon">🕷️</span>
        <span class="button-text">开始抓取数据</span>
    `;
    
    button.style.cssText = `
        position: fixed;
        top: 20px;
        left: 20px;
        z-index: 9999;
        width: 40px;
        height: 40px;
        padding: 8px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.3s ease;
        overflow: hidden;
        white-space: nowrap;
        display: flex;
        align-items: center;
        justify-content: center;
    `;

    const style = document.createElement('style');
    style.textContent = `
        .spider-icon {
            font-size: 20px;
            display: inline-block;
            transition: all 0.3s ease;
        }
        
        .button-text {
            opacity: 0;
            width: 0;
            display: inline-block;
            margin-left: 0;
            transition: all 0.3s ease;
            overflow: hidden;
        }
        
        button:hover {
            width: 140px !important;
            background-color: #45a049 !important;
        }
        
        button:hover .spider-icon {
            margin-right: 8px;
        }
        
        button:hover .button-text {
            opacity: 1;
            width: auto;
            margin-left: 4px;
        }
    `;
    document.head.appendChild(style);

    button.addEventListener('click', scrapeData);
    document.body.appendChild(button);
}

// 获取干净的文本内容
function getCleanText(element) {
    if (!element) return '';
    return element.innerText.trim();
}

// 主要的数据抓取函数
function scrapeData() {
    let data = {
        标题: document.querySelector('.house-title h1')?.innerText.trim(),
        标签: Array.from(document.querySelectorAll('.house-update-info span'))
                  .filter(item => !item.classList.contains('up'))
                  .map(item => item.innerText.trim()),
        发布日期: document.querySelector('.house-update-info .up')?.innerText.replace('发布于','').trim(),
        价格: document.querySelector('.house_basic_title_money_num')?.innerText.trim() + document.querySelector('.house_basic_title_money_unit')?.innerText.trim(),
        平均单价: document.querySelector('.house_basic_title_money_num_second')?.innerText.trim().split('（')[0].trim(),
        建筑面积: document.querySelector('.house_basic_title_info .up')?.innerText.trim(),
        厂房类型: document.querySelectorAll('.house_basic_title_info .up')[1]?.innerText.trim(),
        厂房新旧: document.querySelectorAll('.house_basic_title_info .up')[2]?.innerText.trim(),
        区域: document.querySelector('.house_basic_title_info_2 p:first-child')?.innerText.replace(/区\s*域\s*：/,'').trim().split('-')[0].trim(),
        街道: document.querySelector('.house_basic_title_info_2 p:first-child')?.innerText.replace('区域：','').trim().split('-')[1].trim(),
        地址: document.querySelector('.house_basic_title_info_2 .address')?.innerText.trim(),
        基本信息: (() => {
            const params = {};
            document.querySelectorAll('#jichu .intro-item').forEach(item => {
                const key = item.querySelector('.title')?.innerText.trim() || '';
                const value = item.querySelector('.content')?.innerText.trim() || '';
                if (key) params[key] = value;
            });
            return params;
        })(),
        内部参数: (() => {
            const params = {};
            document.querySelectorAll('.general-item.general-intro .intro-item').forEach(item => {
                const key = item.querySelector('.title')?.innerText.trim() || '';
                const value = item.querySelector('.content')?.innerText.trim() || '';
                if (key) params[key] = value;
            });
            return params;
        })(),
        描述: document.querySelector('.des-item .detail')?.innerText.trim() ||
              document.querySelector('.general-item.general-miaoshu .detail')?.innerText.trim(),
        图集: (() => {
            const images = Array.from(document.querySelectorAll('.general-pic-list img'));
            return {
                count: images.length,
                photos: images.map(img => img.src)
            };
        })()
    };

    // 存储数据到storage
    chrome.storage.local.set({ scrapedData: data });
    
    // 显示数据面板
    showDataPanel(data);
}

// 创建并显示数据面板
function showDataPanel(data) {
    // 移除已存在的面板
    const existingPanel = document.getElementById('data-panel');
    if (existingPanel) {
        existingPanel.remove();
    }

    // 创建面板
    const panel = document.createElement('div');
    panel.id = 'data-panel';
    panel.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: white;
        padding: 20px;
        z-index: 9999;
        display: flex;
        flex-direction: column;
    `;

    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        #data-panel {
            resize: both;
            overflow: auto;
        }
        #data-panel .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        #data-panel button {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            color: white;
            font-weight: bold;
            transition: opacity 0.2s;
            white-space: nowrap;
        }
        #data-panel button:hover {
            opacity: 0.9;
        }
        #data-panel .content-container {
            flex: 1;
            overflow: auto;
            position: relative;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 10px;
            margin-top: 10px;
        }
        #data-panel pre {
            background-color: #1e1e1e;
            color: #d4d4d4;
            padding: 15px;
            border-radius: 4px;
            white-space: pre-wrap;
            word-wrap: break-word;
            font-family: Consolas, Monaco, 'Courier New', monospace;
            font-size: 14px;
            line-height: 1.5;
            margin: 0;
            height: 100%;
            box-sizing: border-box;
            overflow: auto;
        }
        #data-panel .resize-handle {
            position: absolute;
            width: 10px;
            height: 10px;
            background: #4CAF50;
            cursor: se-resize;
        }
        #data-panel .resize-handle.top-left { top: 0; left: 0; cursor: nw-resize; }
        #data-panel .resize-handle.top-right { top: 0; right: 0; cursor: ne-resize; }
        #data-panel .resize-handle.bottom-left { bottom: 0; left: 0; cursor: sw-resize; }
        #data-panel .resize-handle.bottom-right { bottom: 0; right: 0; cursor: se-resize; }
        #data-panel .panel-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        #data-panel .window-controls {
            display: flex;
            gap: 10px;
        }
        #data-panel .window-controls button {
            padding: 4px 8px;
            min-width: 60px;
        }
    `;
    document.head.appendChild(style);

    // 创建面板头部
    const header = document.createElement('div');
    header.className = 'panel-header';
    
    // 添加按钮组
    const buttonGroup = document.createElement('div');
    buttonGroup.className = 'button-group';

    // 复制按钮
    const copyBtn = document.createElement('button');
    copyBtn.textContent = '复制数据';
    copyBtn.style.backgroundColor = '#008CBA';
    copyBtn.onclick = () => {
        navigator.clipboard.writeText(JSON.stringify(data, null, 2))
            .then(() => {
                copyBtn.textContent = '已复制!';
                setTimeout(() => {
                    copyBtn.textContent = '复制数据';
                }, 2000);
            });
    };
    buttonGroup.appendChild(copyBtn);

    // 下载JSON按钮
    const downloadJSONBtn = document.createElement('button');
    downloadJSONBtn.textContent = '下载JSON';
    downloadJSONBtn.style.backgroundColor = '#673AB7';
    downloadJSONBtn.onclick = () => {
        const fileName = `${data.标题 || '58同城厂房'}_${new Date().toLocaleString().replace(/[\/\s:]/g, '_')}.json`;
        const jsonString = JSON.stringify(data, null, 2);
        
        // 创建下载链接
        const downloadLink = document.createElement('a');
        downloadLink.href = 'data:application/json;charset=utf-8,' + encodeURIComponent(jsonString);
        downloadLink.download = fileName;
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    };
    buttonGroup.appendChild(downloadJSONBtn);

    // 下载图片按钮
    const downloadImagesBtn = document.createElement('button');
    downloadImagesBtn.textContent = '下载图片';
    downloadImagesBtn.style.backgroundColor = '#FF5722';
    downloadImagesBtn.onclick = () => {
        const images = data.图集.photos;
        if (!images || images.length === 0) {
            alert('没有找到图片！');
            return;
        }

        // 创建进度显示元素
        const progressDiv = document.createElement('div');
        progressDiv.style.cssText = `
            margin-top: 10px;
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 4px;
        `;
        contentContainer.insertBefore(progressDiv, pre);

        // 下载所有图片
        let downloadedCount = 0;
        const timestamp = new Date().toLocaleString().replace(/[\/\s:]/g, '_');

        const downloadNextImage = (index) => {
            if (index >= images.length) {
                progressDiv.textContent = `下载完成！共 ${images.length} 张图片`;
                setTimeout(() => {
                    progressDiv.remove();
                }, 3000);
                return;
            }

            const imageUrl = images[index];
            const fileName = `${data.标题 || '58同城厂房'}_${timestamp}_图片${index + 1}.jpg`;

            progressDiv.textContent = `正在下载: ${index + 1}/${images.length} 张图片`;

            chrome.runtime.sendMessage({
                action: 'downloadImage',
                imageUrl: imageUrl,
                fileName: fileName
            }, () => {
                downloadedCount++;
                // 延迟500ms后下载下一张
                setTimeout(() => {
                    downloadNextImage(index + 1);
                }, 500);
            });
        };

        // 开始下载第一张图片
        downloadNextImage(0);

        downloadImagesBtn.textContent = '下载中...';
        setTimeout(() => {
            downloadImagesBtn.textContent = '下载图片';
        }, 3000);
    };
    buttonGroup.appendChild(downloadImagesBtn);

    header.appendChild(buttonGroup);

    // 添加窗口控制按钮
    const windowControls = document.createElement('div');
    windowControls.className = 'window-controls';

    // 最小化按钮
    const minimizeBtn = document.createElement('button');
    minimizeBtn.textContent = '最小化';
    minimizeBtn.style.backgroundColor = '#FFC107';
    minimizeBtn.onclick = () => {
        panel.style.height = '60px';
        panel.style.overflow = 'hidden';
        minimizeBtn.style.display = 'none';
        maximizeBtn.style.display = 'inline-block';
    };
    windowControls.appendChild(minimizeBtn);

    // 最大化按钮
    const maximizeBtn = document.createElement('button');
    maximizeBtn.textContent = '最大化';
    maximizeBtn.style.backgroundColor = '#2196F3';
    maximizeBtn.style.display = 'none';
    maximizeBtn.onclick = () => {
        panel.style.height = '100%';
        panel.style.overflow = 'auto';
        maximizeBtn.style.display = 'none';
        minimizeBtn.style.display = 'inline-block';
    };
    windowControls.appendChild(maximizeBtn);

    // 关闭按钮
    const closeBtn = document.createElement('button');
    closeBtn.textContent = '关闭';
    closeBtn.style.backgroundColor = '#f44336';
    closeBtn.onclick = () => panel.remove();
    windowControls.appendChild(closeBtn);

    header.appendChild(windowControls);
    panel.appendChild(header);

    // 创建内容容器
    const contentContainer = document.createElement('div');
    contentContainer.className = 'content-container';

    // 显示JSON数据
    const pre = document.createElement('pre');
    pre.textContent = JSON.stringify(data, null, 2);
    contentContainer.appendChild(pre);

    // 添加调整大小的手柄
    const positions = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
    positions.forEach(pos => {
        const handle = document.createElement('div');
        handle.className = `resize-handle ${pos}`;
        contentContainer.appendChild(handle);
    });

    panel.appendChild(contentContainer);
    document.body.appendChild(panel);

    // 添加拖动调整大小功能
    let isResizing = false;
    let currentHandle = null;
    let startX, startY, startWidth, startHeight;

    function startResize(e, handle) {
        isResizing = true;
        currentHandle = handle;
        startX = e.clientX;
        startY = e.clientY;
        startWidth = panel.offsetWidth;
        startHeight = panel.offsetHeight;
        document.addEventListener('mousemove', resize);
        document.addEventListener('mouseup', stopResize);
    }

    function resize(e) {
        if (!isResizing) return;

        const dx = e.clientX - startX;
        const dy = e.clientY - startY;

        switch(currentHandle.className.split(' ')[1]) {
            case 'top-left':
                panel.style.width = (startWidth - dx) + 'px';
                panel.style.height = (startHeight - dy) + 'px';
                break;
            case 'top-right':
                panel.style.width = (startWidth + dx) + 'px';
                panel.style.height = (startHeight - dy) + 'px';
                break;
            case 'bottom-left':
                panel.style.width = (startWidth - dx) + 'px';
                panel.style.height = (startHeight + dy) + 'px';
                break;
            case 'bottom-right':
                panel.style.width = (startWidth + dx) + 'px';
                panel.style.height = (startHeight + dy) + 'px';
                break;
        }
    }

    function stopResize() {
        isResizing = false;
        document.removeEventListener('mousemove', resize);
        document.removeEventListener('mouseup', stopResize);
    }

    document.querySelectorAll('.resize-handle').forEach(handle => {
        handle.addEventListener('mousedown', (e) => startResize(e, handle));
    });
}

// 初始化
removeAntiCopy();
window.addEventListener('load', createTriggerButton); 